<template>
  <div v-loading="loading" class="promote-config">
    <div class="app-main-content-box form">
      <el-form ref="form" :model="form" :rules="rules" size="small" label-width="120px">
        <!-- 员工 -->
        <app-main-sub-title title="员工推广提成" />
        <el-form-item label="启用提成功能：">
          <el-switch v-model="form.enableEmpBonus" />
        </el-form-item>
        <div class="mb-20" v-if="form.enableEmpBonus">
          <span class="font-14 form-hd_xing mr-10">请选择奖励方式: </span>
          <el-radio-group v-model="form.grantWay">
            <el-radio :label="1">
              <span class="mr-10">商户线下奖励</span>
              <el-tooltip effect="dark" placement="bottom">
                <div slot="content">表示员工推广奖励系统，只做记录。商户自己奖励给员工</div>
                <svg-icon icon-class="i-tips" />
              </el-tooltip>
            </el-radio>
            <el-radio :label="2">
              <span class="mr-10">线上分账</span>
              <el-tooltip effect="dark" placement="bottom">
                <div slot="content">表示产生员工推广奖励，系统自动分账至员工收款账号里<br />注：员工提成金额将按照T+1结算到员工收款账号；（T：指周一至周五，如周五产生交易将下周一结算）<br />如员工没设置收款账号，员工提成报表将记录发放失败，商户自行线下处理。</div>
                <svg-icon icon-class="i-tips" />
              </el-tooltip>
            </el-radio>
            <!-- <el-radio :label="3">
              <span class="mr-10">奖励至员工会员余额</span>
              <el-tooltip effect="dark" placement="bottom">
                <div slot="content">表示产生员工推广奖励，系统直接把奖励放入员工店铺会员卡余额里；<br />当员工还不是商户会员，员工提成报表将记录发放失败，商户自行线下处理。</div>
                <svg-icon icon-class="i-tips" />
              </el-tooltip>
            </el-radio> -->
          </el-radio-group>
        </div>
        <!-- <el-form-item> -->
        <el-collapse-transition>
          <el-card v-if="form.enableEmpBonus" style="margin-bottom:10px;">
            <el-form-item label="提成方式：" prop="empType">
              <el-form-item prop="openCardPermill">
                <el-checkbox v-model="form.empType" label="openCard">顾客开卡金额的百分之</el-checkbox>&nbsp;&nbsp;
                <el-input
                  v-model="form.openCardPermill"
                  :disabled="!form.empType.includes('openCard')"
                  placeholder="请输入"
                  size="small"
                  class="input"
                  maxlength="4"
                />
              </el-form-item>
              <el-form-item prop="firstRechargePermill">
                <el-checkbox v-model="form.empType" label="firstRecharge">顾客充值（含充值开卡）金额的百分之</el-checkbox>&nbsp;&nbsp;
                <el-input
                  v-model="form.firstRechargePermill"
                  :disabled="!form.empType.includes('firstRecharge')"
                  placeholder="请输入"
                  size="small"
                  class="input"
                  maxlength="4"
                />
              </el-form-item>

              <el-form-item prop="orderPayPermill">
                <el-checkbox v-model="form.empType" label="payPermill">顾客消费订单实付金额的百分之</el-checkbox>&nbsp;&nbsp;
                <el-input
                  v-model="form.orderPayPermill"
                  :disabled="!form.empType.includes('payPermill')"
                  placeholder="请输入"
                  size="small"
                  class="input"
                  maxlength="4"
                />
              </el-form-item>
              <el-form-item>
                注：商城/点餐/预订/码牌支付订单实付金额指订单商品优惠后的总额，不含运费
              </el-form-item>
            </el-form-item>
          </el-card>
        </el-collapse-transition>
        <!-- </el-form-item> -->
        <!-- 顾客 -->
        <app-main-sub-title title="顾客推广奖励" />
        <el-form-item label="启用奖励功能：">
          <el-switch v-model="form.enableMemberBonus" />
        </el-form-item>
        <!-- <el-form-item> -->
        <el-collapse-transition>
          <el-card v-if="form.enableMemberBonus" style="margin-bottom:10px;">
            <!-- <span>如果顾客不是会员则会奖励失效</span> -->
            <!-- <el-form-item label-width="20px">
              <el-tag>
                <i class="el-icon-warning" />&nbsp;温馨提示：如果顾客不是会员则奖励会失效。
              </el-tag>
            </el-form-item> -->

            <el-tabs v-model="activeName">
              <el-tab-pane
                v-for="(tabItem, tabIdx) in form.memberConfigVos"
                :key="tabItem.name"
                :label="tabItem.label"
                :name="tabItem.name"
              >
                <el-form-item
                  v-if="(tabItem.bonusType !== 1) && (tabItem.bonusType === ~~activeName + 1)"
                  label="限制设置："
                  :prop="`memberConfigVos[${tabIdx}].limitAmount`"
                  :rules="{required: tabItem.openLimitSetting,validator: validateLimitAmount, trigger: ['blur', 'change']}"
                >
                  <el-checkbox v-model="tabItem.openLimitSetting">{{tabItem.name | limitLabel}}</el-checkbox>
                  <div class="mx-10" style="display: inline-block;">
                    <el-input
                      v-model="tabItem.limitAmount"
                      size="small"
                      class="input"
                      :disabled="!tabItem.openLimitSetting"
                    />
                  </div>
                  <span>元享受奖励</span>

                  <p v-show="tabItem.name === '2'">注：订单实付金额指订单商品优惠后的总额，不含运费</p>
                </el-form-item>
                <el-form-item
                  v-if="(tabItem.bonusType ==3) "
                  label="参与商品："
                  :prop="`memberConfigVos[${tabIdx}].productType`"
                  :rules="{required: true,validator: validateLimitAmount, trigger: ['blur', 'change']}"
                >
                    <el-radio-group v-model="tabItem.productType">
                      <el-radio :label="1">全部商品</el-radio>
                      <el-radio :label="2">部分商品</el-radio>
                    </el-radio-group>
                  <div v-if="tabItem.productType == '2'" class="add_text"><el-button @click="openAddDialog('add')">添加商品</el-button>&emsp;&emsp;&emsp;<el-button type="text" @click="openAddDialog('edit')">已选{{selectedProduct.length}}件商品</el-button></div>
                </el-form-item>

                <!-- 奖励的类型 -->
                <el-form-item
                  v-if="tabItem.bonusType === ~~activeName + 1"
                  label="奖励的类型："
                  :prop="`memberConfigVos[${tabIdx}].memberType`"
                  :rules="{required: true, validator: validateMemberType, trigger: ['blur', 'change']}"
                >
                  <el-checkbox-group v-model="tabItem.memberType" @change="(val) => memberTypeChange(val, tabIdx)">>
                    <el-checkbox label="balance" name="memberType">余额</el-checkbox>
                    <el-checkbox label="points" name="memberType">积分</el-checkbox>
                    <el-checkbox label="cardCoupon" name="memberType">卡券
                    </el-checkbox>
                    <!-- <el-checkbox :disabled="form.memberType.includes('cardCoupon')" label="coupon" name="memberType">优惠券(已弃用)
                    </el-checkbox> -->
                  </el-checkbox-group>
                </el-form-item>

                <!-- 奖励会员余额 -->
                <el-form-item
                  v-if="tabItem.memberType.includes('balance') && tabItem.bonusType === ~~activeName + 1"
                  label="赠送会员余额："
                  :prop="`memberConfigVos[${tabIdx}].balanceBonus`"
                  :rules="{required: tabItem.memberType.includes('balance'), validator: validateBalanceBonus, trigger: ['blur', 'change']}"
                >
                  <el-input
                    v-model="tabItem.balanceBonus"
                    placeholder="请输入"
                    size="small"
                    class="input"
                    maxlength="10"
                  />&nbsp;&nbsp;元
                </el-form-item>

                <!-- 奖励会员积分 -->
                <el-form-item
                  v-if="tabItem.memberType.includes('points') && tabItem.bonusType === ~~activeName + 1"
                  label="赠送会员积分："
                  :prop="`memberConfigVos[${tabIdx}].pointsBonus`"
                  :rules="{required: tabItem.memberType.includes('points'), validator: validatePointsBonus, trigger: ['blur', 'change']}"
                >
                  <el-input
                    v-model="tabItem.pointsBonus"
                    placeholder="请输入"
                    maxlength="7"
                    size="small"
                    class="input"
                  />&nbsp;&nbsp;个
                </el-form-item>

                <!-- 奖励优惠券 券v2 -->
                <!-- 这里不能用v-show 表单校验问题 -->
                <el-form-item
                  v-if="(tabItem.memberType.includes('cardCoupon')||tabItem.memberType.includes('coupon')) && tabItem.bonusType === ~~activeName + 1"
                  :rules="{type: 'array', required: tabItem.memberType.includes('cardCoupon')||tabItem.memberType.includes('coupon'), validator: validateCouponBonus, trigger: 'change'}"
                  :label="tabItem.memberType.includes('cardCoupon')?'赠送卡券':'赠送券'"
                  :prop="`memberConfigVos[${tabIdx}].bonusCouponVos`"
                >
                  <div class="card-coupon-container">
                    <el-table
                      :data="tabItem.bonusCouponVos"
                      border
                      stripe
                      size="small"
                      empty-text="暂未配置"
                      style="width: 100%"
                    >
                      <el-table-column prop="couponId" label="批次号" />
                      <el-table-column prop="couponName" label="卡券名称" />
                      <el-table-column prop="couponType" label="卡券类型">
                        <template slot-scope="scope">
                          {{ $store.getters.cardCouponTypeKeyOptions[scope.row.couponType]||"--" }}
                        </template>
                      </el-table-column>
                      <el-table-column prop="amount" label="数量" width="170px">
                        <template slot-scope="scope">
                          <el-input-number
                            v-model="scope.row.amount"
                            :min="1"
                            :max="99"
                            maxlength="2"
                            label="数量"
                            style="margin-top: 18px"
                          />
                        </template>
                      </el-table-column>
                      <el-table-column label="操作" width="80">
                        <template slot-scope="scope">
                          <el-button type="text" @click="delCardCoupon(scope.$index)">删除</el-button>
                        </template>
                      </el-table-column>
                    </el-table>
                    <el-button
                      v-if="tabItem.memberType.includes('cardCoupon')"
                      :disabled="tabItem.bonusCouponVos && tabItem.bonusCouponVos.length>=10"
                      type="text"
                      icon="el-icon-plus"
                      style="display:block"
                      @click.native.prevent="openDialogCardCouponTable"
                    >增加卡券
                    </el-button>
                    <!--<el-button-->
                    <!--  v-if="form.memberType.includes('coupon')"-->
                    <!--  disabled="false"-->
                    <!--  type="text"-->
                    <!--  icon="el-icon-plus"-->
                    <!--  style="display:block"-->
                    <!--  @click.native.prevent="openCouponList"-->
                    <!--&gt;增加券-->
                    <!--</el-button>-->
                    <div style="font-size: 12px;color: #606266">单次最多添加卡券种类不超过10种，卡券总数量不超过30张（因为微信限制，暂不支持配置微信商家券）</div>
                  </div>
                </el-form-item>

              </el-tab-pane>
            </el-tabs>

          </el-card>
        </el-collapse-transition>
        <!-- </el-form-item> -->
        <!-- 提交 -->
        <el-form-item>
          <el-button round type="primary" @click="onSubmit">保 存</el-button>
          <el-button round @click="initData">重 置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- 券1.0 筛选表格 -->
    <dialog-coupon-list ref="dialogCouponList" />
    <!--券2.0 筛选表格 -->
    <DialogCardCouponTable ref="dialogCardCouponTable" :card-coupon-type="['cash','discount','exchange','cash_wx_pay','times','gift']" :has-checked-ids="hasCheckedCardCouponIds" />
    <addProductDialog ref="addProductDialog" @dialogClose="dialogClose"   />
    <selectedDialog ref="selectedDialog" @dialogClose="dialogClose"   />
    
  </div>
</template>

<script>
import DialogCouponList from '@/components/DialogCouponList'
import DialogCardCouponTable from '@/components/DialogCardCouponTable'
import addProductDialog from './addProductDialog.vue'
import selectedDialog from './selectedDialog.vue'
import { getVipInviteConfig, updateVipInviteConfig,getSelectedNum,getChooseProducts,productSaveOrUpdate, } from '@/api/vip'
import { validateCustomADecimal, validate0To20ADecimal } from '@/utils/validate'
import { debounce } from '@/utils/index'
import valiteModule from './valiteModule'
import { cloneDeep } from 'lodash-es'
const LABEL = {
  '1': '顾客单次充值金额≥',
  '2': '顾客单次消费订单金额≥'
}
const bonusWayListsMap = {
  balance: 1,
  points: 2,
  cardCoupon: 4
}
const bonusWayListsMapF = {
  1: 'balance',
  2: 'points',
  4: 'cardCoupon'
}
export default {
  components: {
    DialogCouponList,
    DialogCardCouponTable,
    addProductDialog,
    selectedDialog,
  },
  props: {
    tabName: {
      type: String,
      require: true
    }
  },
  data() {
    const _this = this
    /**
     * 表单校验方法相关
     */
    // 百分比0.1到100校验
    const validatePercent1to99 = (rule, value, callback, text) => {
      if (!value) {
        callback(new Error(text))
      } else if (!validateCustomADecimal(value, 2, [100])) {
        callback(new Error('请输入0.1~100正整数，正小数（小数位不超过1位）'))
      } else {
        callback()
      }
    }
    const validatePercent1to20 = (rule, value, callback) => {
      const reg = new RegExp('^((0\\.[1-9])|([1-9])|([1][0-9])|([1][0-9])\\.\\d{1}|([1-2]{0,2}\\.\\d{1})|20)$')
      if (!value) {
        callback(new Error('请输入比例'))
      } else if (!reg.test(value)) {
        callback(new Error('请输入0.1~20正整数，正小数（小数位不超过1位）'))
      } else {
        callback()
      }
    }

    // 如果启用 员工提成的方式 必须选择其中一种
    const validateEmpType = (rule, value, callback) => {
      if (this.form.enableEmpBonus && value.length === 0) {
        callback(new Error('请至少选择一种员工提成方式'))
      } else {
        callback()
      }
    }

    // 这里不是箭头函数，并且这里的this不是vue实例的this，用了bind
    const validateOpen = function(rule, value, callback) {
      if (
        !_this.form.enableEmpBonus ||
          !_this.form.empType.includes(this)
      ) {
        callback()
      } else {
        switch(_this.form.grantWay) {
          case 1:
            validatePercent1to99(rule, value, callback, '请输入比例')
            break;
          case 2:
            validatePercent1to20(rule, value, callback)
            break;
          default:
            callback(new Error('校验错误'))
            break;
        }

      }
    }

    //  校验优惠券id是否已经过期
    // const validateCouponBonusId = (rule, value, callback) => {
    //   if (this.$isNull(value)) {
    //     callback('请选择优惠券')
    //   } else if (this.invalidCouponIds.includes(value)) {
    //     callback(new Error('该券已过期或已删除，请更换其它券'))
    //   } else {
    //     callback()
    //   }
    // }
    return {
      /**
       * 表单校验字段相关
       */
      rules: {
        // 员工提成的方式
        empType: [
          {
            required: true,
            validator: validateEmpType,
            trigger: 'change'
          }
        ],
        // 员工提成的方式 顾客首充充值比例
        firstRechargePermill: [
          {
            required: true,
            validator: validateOpen.bind('firstRecharge'),
            trigger: ['blur', 'change']
          }
        ],
        // 员工提成的方式 顾客开卡比例
        openCardPermill: [
          {
            required: this.openLimitSetting,
            validator: validateOpen.bind('openCard'),
            trigger: ['blur', 'change']
          }
        ],
        // 优惠券判断失效
        // couponBonusId: [
        //   {
        //     required: true,
        //     validator: validateCouponBonusId,
        //     trigger: ['blur', 'change']
        //   }
        // ],
        orderPayPermill: [
          {
            required: true,
            validator: validateOpen.bind('payPermill'),
            trigger: ['blur', 'change']
          }
        ]
      },
      // 配置
      // 状态
      loading: false,
      // 数据
      hasCheckedCardCouponIds: [], // 当前已选择的优惠券
      // invalidCouponIds: [], // 失效的优惠券id
      form: {
        enableEmpBonus: false, // 是否启用员工提成
        empType: [], // 员工提成方式
        grantWay: 1, // 奖励方式
        enableMemberBonus: false, // 是否启用顾客奖励
        // memberType: [], // 顾客奖励方式
        memberConfigVos: [
          {
            label: '开卡奖励',
            name: '0',
            openLimitSetting: false,
            bonusCouponVos: [],
            bonusType: 1, // 奖励的行为1开卡奖励2充值奖励3消费奖励
            bonusWayLists: [],
            balanceBonus: '', // 赠送余额
            pointsBonus: '', //  赠送会员积分
            limitAmount: '', // 限制设置金额
            memberType: [],
          },
          {
            label: '充值奖励',
            name: '1',
            openLimitSetting: false,
            bonusCouponVos: [],
            bonusType: 2, // 奖励的行为1开卡奖励2充值奖励3消费奖励
            bonusWayLists: [], //  1余额2积分4卡券
            balanceBonus: '', // 赠送余额
            pointsBonus: '', //  赠送会员积分
            limitAmount: '', // 限制设置金额
            memberType: []
          },
          {
            label: '消费奖励',
            name: '2',
            openLimitSetting: false,
            bonusCouponVos: [],
            bonusType: 3, // 奖励的行为1开卡奖励2充值奖励3消费奖励
            bonusWayLists: [],
            balanceBonus: '', // 赠送余额
            pointsBonus: '',  //  赠送会员积分
            limitAmount: '', // 限制设置金额
            memberType: [],
            productType: 1
          }
        ]
      },
      activeName: '0',
      dataPar:{
        arr:'1'
      },
      // 已选商品数量
      selectedNum:0,
      // 已选商品
      selectedProduct:[]
    }
  },
  watch: {
    tabName(val) {
      if (val === 'config') {
        this.initData()
      }
    },
    'form.empType'(val) {
      if (val.length !== 0) {
        this.$refs.form.clearValidate(['empType'])
      }
    },
    'form.grantWay'() {
      this.$refs.form.validateField(['openCardPermill'])
      this.$refs.form.validateField(['firstRechargePermill'])
      this.$refs.form.validateField(['orderPayPermill'])
    }
    // // 'form.memberType'(val) {
    //   if (val.length !== 0) {
    //     this.$refs.form.clearValidate(['memberType'])
    //   }
    // }
  },
  filters: {
    limitLabel(val) {
      return LABEL[val] || ''
    }
  },
  mounted() {
    this.initData()
  },
  methods: {
    /**
     *  获取数据
     */
    // 获取推广配置
    initData() {
      this.loading = true
      getVipInviteConfig().then(res => {
        res.data.empType = []
        // res.data.memberType = []
        if (res.data.firstRechargePermill) {
          res.data.empType.push('firstRecharge')
          res.data.firstRechargePermill = res.data.firstRechargePermill / 10
        }
        if (res.data.openCardPermill) {
          res.data.empType.push('openCard')
          res.data.openCardPermill = res.data.openCardPermill / 10
        }
        if(res.data.orderPayPermill) {
           res.data.empType.push('payPermill')
           res.data.orderPayPermill = res.data.orderPayPermill / 10
        }

        if(res.data.memberConfigVos) {
          const cloneData = cloneDeep(res.data.memberConfigVos)
          Object.assign(res.data.memberConfigVos, this.form.memberConfigVos)
          cloneData.forEach((item,index) => {
            item.memberType = []
            item.bonusWayLists.forEach(bonusWay => {
              if(bonusWay) {
                item.memberType.push(bonusWayListsMapF[bonusWay])
              }
            })
             // 判断是否有余额
            if(item.balanceBonus) {
              item.balanceBonus = item.balanceBonus
            }
            // // 判断是否有积分
            // if (item.pointsBonus) {
            //   item.memberType.push('points')
            // }
            // 判断是否有券

            if(!item.bonusCouponVos || !item.bonusCouponVos.length) {
              item.bonusCouponVos = []
            }
            res.data.memberConfigVos.forEach((i, idx) => {
            if( i.bonusType === item.bonusType) {
              Object.assign(i, item)
            }
            i.limitAmount && (i.openLimitSetting = true)
          })
          })
          // res.data.memberConfigVos.forEach((i, idx) => {
          //   if(cloneData[idx] && (i.bonusType === cloneData[idx].bonusType)) {
          //     Object.assign(i, cloneData[idx])
          //   }
          //   i.limitAmount && (i.openLimitSetting = true)
          // })
        } else {
          res.data.memberConfigVos = this.form.memberConfigVos
        }
        this.form = res.data
        console.log(this.form)
      }).finally(() => {
        this.loading = false
      })
      
      this.getChooseProducts()
    },
    getChooseProducts(){
      // 获取已选商品
      getChooseProducts({}).then((res) => {
        if (res.code == 0) {
          this.selectedProduct = res.data;
        }
      });
    },
    
    // 打开新增商品弹窗
    openAddDialog(type){
      console.log(type)
      let {form:{id},selectedProduct} = this
      type=='add'?this.$refs.addProductDialog.openDialog(selectedProduct):this.$refs.selectedDialog.openDialog(selectedProduct)
    },
    dialogClose(data){
      this.selectedProduct = data.chooseProducts
    },
    // // 打开已选商品弹窗
    // openSelectDialog(){
    //   this.$refs.selectedDialog.openDialog(this.form.id)
    // },

    // 根据ids获取当前优惠券列表
    // initCouponList() {
    //   const ids = this.hasCheckedCardCouponIds
    //   this.loading = true
    //   getCouponListByIds({ ids })
    //     .then(res => {
    //       if (res.data) {
    //         res.data.forEach(v => {
    //           if (v.status === 3 || v.logicDelete) {
    //             this.invalidCouponIds.push(v.id)
    //           }
    //         })
    //       }
    //     })
    //     .finally(() => {
    //       this.loading = false
    //     })
    // },

    /**
     *  按钮组
     */
    // 保存推广配置
    onSubmit: debounce(function() {
      let {form:{memberConfigVos:list},selectedProduct} = this
      let flagPar = ''
      if(list&&list.length>0){
        list.forEach( item=> {
          if(item.bonusType==3){
            flagPar = item
          }
        })
      }
      if(flagPar&&flagPar.productType == 2 &&selectedProduct.length<1){
        this.$message({
          type:'error',
          message:'请选择参与商品之后再进行保存'
        })
        return
      }
      this.$refs.form.validate(valid => {
        if (valid) {
          // 格式化数据
          const params = cloneDeep(this.form)
          if(!params.empType.includes('firstRecharge')) {
            delete params.firstRechargePermill
          } else {
            params.firstRechargePermill = params.firstRechargePermill ? this.$math.mul(params.firstRechargePermill, 10, 0) : null
          }
          if(!params.empType.includes('openCard')) {
            delete params.openCardPermill
          } else {
            params.openCardPermill = params.openCardPermill ? this.$math.mul(params.openCardPermill, 10, 0) : null
          }
          if(!params.empType.includes('payPermill')) {
            delete params.orderPayPermill
          } else {
            params.orderPayPermill = params.orderPayPermill ? this.$math.mul(params.orderPayPermill, 10, 0) : null
          }
          if (params.enableMemberBonus) {
            params.memberConfigVos.forEach(i => {
              if (!i.memberType.includes('balance')) {
               delete i.balanceBonus
              }
              if(!i.openLimitSetting) {
                delete i.limitAmount
              }
              if (!i.memberType.includes('points')) {
                delete i.pointsBonus
              }
              i.bonusWayLists = [...new Set(i.bonusWayLists)]
              if (!i.memberType.includes('cardCoupon')) {
                delete i.bonusCouponVos
              }
            })
          } else {
            delete params.memberConfigVos
          }

          // 删除多选状态
          delete params.empType
          // 删除 memberConfigVos memberType 没选择的项
          if(params.memberConfigVos) {
            params.memberConfigVos = params.memberConfigVos.filter(i => i.memberType.length)
          }
          // delete params.memberType
          this.loading = true
          updateVipInviteConfig(params)
            .then(res => {
              this.loading = false
              this.$notify({
                title: '成功',
                message: '保存成功',
                type: 'success',
                duration: 2000,
                offset: 40
              })
              this.initData()
            })
            .catch(() => {
              this.loading = false
            })
            productSaveOrUpdate({
            addProductIds:selectedProduct,
            inviteConfigId:params.id,
            }).then((res) => {
              if (res.code == 0) {}
            });
        }
      })
    }, 300),

    // 新增优惠券
    openCouponList() {
      this.hasCheckedCardCouponIds = []
      this.form.memberConfigVos[this.activeName].bonusCouponVos.forEach(v => {
        this.hasCheckedCardCouponIds.push(v.couponId)
      })
      this.$refs.dialogCouponList.open(this.hasCheckedCardCouponIds, 1).then(res => {
        this.$refs.form.clearValidate(['bonusCouponVos'])
        const params = Object.assign({}, res)
        // const params = {
        //   couponId: res.id,
        //   amount: 1,
        //   couponName: res.couponName
        // }
        this.form.memberConfigVos[this.activeName].bonusCouponVos.push(params)
      })
    },

    //  新增优惠券 v2
    openDialogCardCouponTable() {
      this.hasCheckedCardCouponIds = []
      this.form.memberConfigVos[this.activeName].bonusCouponVos.forEach(v => {
        this.hasCheckedCardCouponIds.push(v.couponId)
      })
      this.$nextTick(() => {
        this.$refs.dialogCardCouponTable.open().then(res => {
          this.$refs.form.clearValidate(['couponBonus'])
          this.form.memberConfigVos[this.activeName].bonusCouponVos = this.form.memberConfigVos[this.activeName].bonusCouponVos.concat(res)
        })
      })
    },

    // 删除优惠券
    delCardCoupon(index) {
      this.$refs.form.clearValidate(['bonusCouponVos[' + index + '].couponId'])
      this.form.memberConfigVos[this.activeName].bonusCouponVos.splice(index, 1)
      if (this.form.memberConfigVos[this.activeName].bonusCouponVos.length <= 10) {
        this.$refs.form.validateField(['bonusCouponVos'])
      }
    },

    /**
     * 状态
     */
    // 赠送类型
    memberTypeChange(val, idx) {
      if(!val) return
      const bonusWayLists = val.map((i, idx) => bonusWayListsMap[val[idx]])
      this.form.memberConfigVos[idx].bonusWayLists  = bonusWayLists
      if (!val.includes('cardCoupon') && !val.includes('coupon')) {
        this.form.memberConfigVos[idx].bonusCouponVos = []
      }
      // console.log(this.form.memberConfigVos[idx].bonusWayLists)
    },

    ...valiteModule
  }
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
/* 券列表 */
.card-coupon-container {
  max-width: 800px;
  margin-bottom: 10px;

  //.coupon-list {
  //  margin-top: 18px;
  //  width: 100%;
  //  display: flex;
  //  align-items: center;
  //  justify-content: space-between;
  //
  //  .coupon-info {
  //    min-width: 250px;
  //    color: #606266;
  //    margin-right: 20px;
  //    line-height: 1.2;
  //  }
  //}
}
.add_text{
  color: #86c8ff;
}

.promote-config {
  .form {
    .input {
      width: 120px;
    }

    .input-append-250 {
      width: 250px;
    }
  }
  .form-hd_xing::before {
    content: '*';
    color: #EC4040;
    margin-right: 4px;
  }
}
</style>
